package com.fausto.learnimprint.core.service.impl

import cn.hutool.core.lang.id.NanoId
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.fausto.learnimprint.core.mapper.MessageMapper
import com.fausto.learnimprint.core.model.entity.Message
import com.fausto.learnimprint.core.service.IMessageService
import com.fausto.learnimprint.core.service.IUserService
import com.fausto.learnimprint.utils.RequestUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDateTime
import javax.servlet.http.HttpServletRequest

/**
 *
 *
 * 服务实现类
 *
 *
 * @author fausto
 * @since 2022-03-28
 */
@Service
class MessageServiceImpl :
    ServiceImpl<MessageMapper, Message>(),
    IMessageService {

    @Autowired
    lateinit var ipUtil: RequestUtil

    @Autowired
    lateinit var request: HttpServletRequest

    @Autowired
    lateinit var messageMapper: MessageMapper

    @Autowired
    lateinit var userService: IUserService

    @Transactional(rollbackFor = [Exception::class])
    override fun saveMessage(messageBody: String): Boolean {
        //获取用户信息
        val user = userService.findUserFromContext()
        //判断该用户是否为游客
        val isGuest = userService.getRoles(user).contains("GUEST")
        //留言用户名
        val messageName = if (isGuest) {
            //若游客留言则保存其IP地址
            try {
                ipUtil.getIpAddress(request).unwrap()
            } catch (e: Exception) {
                e.printStackTrace()
                //获取游客IP地址失败
                "游客" + NanoId.randomNanoId(8)
            }
            //否则保存用户名
        } else {
            user.username
        }
        //保存至数据库
        val flag = messageMapper.insert(
            Message().apply {
                this.messageName = messageName
                this.messageBody = messageBody
                this.messageTime = LocalDateTime.now()
            }
        )
        //flag大于0则说明插入成功
        return flag > 0
    }
}